package cn.yx.framework.configuration;

import cn.com.yx.ms.domain.dbmodel.CmdRecord;
import cn.com.yx.ms.domain.mq.MqCommandType;
import cn.com.yx.ms.persistence.CmdRecordMapper;
import cn.com.yx.ms.service.IMqService;
import cn.yx.framework.log.MyLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author ZHUL
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2017-02-13 9:10
 */
@Component
public class MQSend implements RabbitTemplate.ConfirmCallback {

    private static final Logger logger = LoggerFactory.getLogger(MQSend.class);

    private RabbitTemplate rabbitTemplate;

//    @Resource
//    RabbitMQConfig rabbitMQConfig;

    @Resource
    IMqService mqService;

    @Resource
    private CmdRecordMapper cmdRecordMapper;

    // 保存socket会话用Map
    private static Map<String,CmdRecord> websocketMap = new HashMap<String,CmdRecord>();

    //时间比较用参数
    private static Long timeMillions = 0L;

//    @Resource
//    MyWebSocket myWebSocket;

    /**
     * 构造方法注入
     */
    @Autowired
    public MQSend(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        //rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
    }

    /**
     * MQ下行发送
     *
     * @param mqCommandType
     * @param content
     */
    public void sendMsg(String devsn, MqCommandType mqCommandType, String content) {
        try {
//            MqConfig mqConfig = mqService.findOne(mqCommandType.getIndex(), "1");
//            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
//            rabbitTemplate.convertAndSend(rabbitMQConfig.exchangeConfig().getName(),
//                    mqConfig.getRoutingkey(),
//                    content,
//                    correlationId);

            MyWebSocket.sendInfo(devsn, content);

            int length = content.getBytes("UTF-8").length;

             webSocketMapInfo(mqCommandType.getIndex(),mqCommandType.getName(),devsn,length);

            MyLogger.log("/command/下行/" + devsn + "/"
                            + mqCommandType.getIndex() + "-" + mqCommandType.getName() + "/",
                    content);

            System.out.println("[DOWNCMD]系统发送============>" + content);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

    }

    /**
     * 首页动态实时数据采集写入（下行）
     * @param index 指令代码
     * @param name 指令名称
     * @param devsn 设备编号
     * @param length 字符串长度
     */
    private void webSocketMapInfo(int index,String name,String devsn,int length){
//        CmdRecord cmdRecord = new CmdRecord();
//        cmdRecord.setCmdtime(new Date());
//        cmdRecord.setCmdcode(String.valueOf(index));
//        cmdRecord.setCmdname(name);
//        cmdRecord.setCmdtype("response");
//        cmdRecord.setEquipmentno(devsn);
//        cmdRecord.setCmdbytelength(length);
//
//        if(websocketMap.isEmpty()){
//            timeMillions = Calendar.getInstance().getTimeInMillis();
//            websocketMap.put(UUID.randomUUID().toString(),cmdRecord);
//
//        } else {
//            // 超过10分钟则将数据写入DB
//            if(Calendar.getInstance().getTimeInMillis() - timeMillions > 600000){
//                List<CmdRecord> list = new ArrayList<CmdRecord>();
//
//                // 创建时间
//                Date date = new Date();
//
//                // 遍历map，生成对象list
//                for(String key : websocketMap.keySet()){
//                    CmdRecord cr = websocketMap.get(key);
//                    cr.setGuid(key);
//                    cr.setCreatetime(date);
//                    list.add(cr);
//                }
//
//                // cmdRecord 插入操作
//                if(list.size() > 0) {
//                    cmdRecordMapper.insertSelectiveList(list);
//                }
//
//                websocketMap.clear();
//                timeMillions = Calendar.getInstance().getTimeInMillis();
//                websocketMap.put(UUID.randomUUID().toString(),cmdRecord);
//            } else {
//                // 不超过10分钟，写入map
//                websocketMap.put(UUID.randomUUID().toString(),cmdRecord);
//            }
//        }
    }

    public void sendMsg4Up(String devsn, MqCommandType mqCommandType, String content) {
        try {

            MyWebSocketUpdate.sendInfo(devsn, content);

            MyLogger.log("/command/下行/" + devsn + "/"
                            + mqCommandType.getIndex() + "-" + mqCommandType.getName() + "/",
                    content);

            System.out.println("[DOWNCMD]系统发送update============>" + content);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

    }

    /**
     * 回调(已关闭)
     * 接收上行指令位于AmqpConfig的SimpleMessageListenerContainer方法中
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.out.println(" 回调id:" + correlationData);
        if (ack) {
            System.out.println("消息成功消费");
        } else {
            System.out.println("消息消费失败:" + cause);
        }
    }

}
